<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>社区论坛</title>
    <link rel="stylesheet" href="./element-ui/index.css">
    <style>
        :root {
            --primary-color: #409EFF;
            --hover-color: #66b1ff;
            --warning-color: #e6a23c;
        }

        .community-container {
            padding: 30px;
            max-width: 1400px;
            background: #f8f9fa;
        }

        /* 头部升级 */
        .header {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            padding: 20px 30px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }
        .header h1 {
            font-size: 28px;
            color: #303133;
            font-weight: 600;
            letter-spacing: 1px;
        }

        /* 卡片升级 */
        .post-card {
            margin-bottom: 24px;
            transition: all 0.3s cubic-bezier(0.4,0,0.2,1);
            border-radius: 12px !important;
            border: 1px solid #ebeef5;
        }
        .post-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 18px rgba(0,0,0,0.08);
        }

        /* 元信息布局优化 */
        .post-meta {
            display: flex;
            gap: 8px;
            margin: 15px 0;
            flex-wrap: wrap;
        }

        /* 仿微博评论设计 */
        .comment-item {
            margin: 16px 0;
            padding: 16px;
            background: #fff;
            border-radius: 8px;
            border-left: 3px solid var(--primary-color);
            box-shadow: 0 2px 8px rgba(0,0,0,0.03);
        }
        .comment-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 12px;
        }
        .user-name {
            color: #606266;
            font-weight: 500;
        }

        /* 主按钮动效 */
        .el-button--primary {
            transition: all 0.3s;
            background: linear-gradient(135deg, var(--primary-color), #66b1ff);
            border: none !important;
        }
        .el-button--primary:hover {
            transform: scale(1.02);
            box-shadow: 0 4px 12px rgba(64,158,255,0.3);
        }

        /* 图片预览增强 */
        .post-image {
            border-radius: 12px;
            cursor: zoom-in;
            transition: transform 0.3s;
        }
        .post-image:hover {
            transform: scale(1.02);
        }

        /* 分页组件美化 */
        .el-pagination.is-background .el-pager li:not(.disabled).active {
            background: linear-gradient(135deg, var(--primary-color), #66b1ff) !important;
        }

    /*    卡片问题1*/
    /*    .el-col {*/
    /*        display: flex !important; !* 关键属性 *!*/
    /*    }*/

    /*    .post-card {*/
    /*        width: 100%; !* 确保卡片撑满列宽 *!*/
    /*        display: flex;*/
    /*        flex-direction: column;*/
    /*        min-height: 280px; !* 最小高度保障 *!*/
    /*    }*/

    /*    !* 内容区域自动填充 *!*/
    /*    .post-card .el-card__body {*/
    /*        flex: 1;*/
    /*        display: flex;*/
    /*        flex-direction: column;*/
    /*    }*/

    /*    !* 标题限制行数 *!*/
    /*    .post-card h3 {*/
    /*        margin: 0 0 12px 0;*/
    /*        font-size: 16px;*/
    /*        line-height: 1.4;*/
    /*        display: -webkit-box;*/
    /*        -webkit-line-clamp: 2; !* 限制2行 *!*/
    /*        -webkit-box-orient: vertical;*/
    /*        overflow: hidden;*/
    /*    }*/

    /*    !* 元信息底部定位 *!*/
    /*    .post-meta {*/
    /*        margin-top: auto; !* 关键属性 *!*/
    /*        padding-top: 12px;*/
    /*    }*/

    /*    !* 查看按钮底部固定 *!*/
    /*    .post-card .el-button {*/
    /*        margin-top: auto;*/
    /*        align-self: flex-start;*/
    /*        padding-left: 0;*/
    /*    }*/

    /*  卡片问题2  */
        /* 替换原有el-row样式 */
        .el-row {
            column-count: 4; /* 默认4列 */
            column-gap: 15px;
            break-inside: avoid; /* 防止内容断裂 */
        }

        /* 调整列宽响应式 */
        @media (max-width: 1200px) {
            .el-row { column-count: 3; }
        }
        @media (max-width: 992px) {
            .el-row { column-count: 2; }
        }
        @media (max-width: 768px) {
            .el-row { column-count: 1; }
        }

        /* 移除原有el-col设置 */
        .el-col {
            width: 100% !important;
            margin-bottom: 15px;
            display: inline-block; /* 关键属性 */
            vertical-align: top;
        }

        /* 调整卡片样式 */
        .post-card {
            min-height: auto !important; /* 移除固定高度 */
            break-inside: avoid; /* 禁止卡片内部换列 */
            transition: all 0.3s;
            position: relative;
        }

        /* 优化图片显示 */
        .post-image {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
        }

    /*    查看图片*/
        /* 添加图片预览层级修复 */
        .el-image-viewer__wrapper {
            z-index: 3000 !important; /* 需高于对话框的2000 */
        }

        /* 调整对话框层级 */
        .el-dialog__wrapper {
            z-index: 2000;
        }

        /* 修复父容器限制 */
        .post-detail {
            position: static !important; /* 移除相对定位 */
        }
    /*    详情图片问题1*/
    /*    !* 调整详情页图片样式 *!*/
    /*    .post-detail .post-image {*/
    /*        max-width: 80%;*/
    /*        height: auto;*/
    /*        border-radius: 12px;*/
    /*        box-shadow: 0 8px 24px rgba(0,0,0,0.1);*/
    /*        margin: 20px auto;*/
    /*        display: block;*/
    /*        cursor: zoom-in;*/
    /*        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);*/
    /*    }*/

    /*    !* 响应式调整 *!*/
    /*    @media (max-width: 768px) {*/
    /*        .post-detail .post-image {*/
    /*            max-width: 95%;*/
    /*            margin: 15px auto;*/
    /*        }*/
    /*    }*/

    /*    !* 添加悬停动画 *!*/
    /*    .post-detail .post-image:hover {*/
    /*        transform: scale(1.02);*/
    /*        box-shadow: 0 12px 32px rgba(0,0,0,0.15);*/
    /*    }*/

    /*    !* 图片容器优化 *!*/
    /*    .post-content {*/
    /*        text-align: center;*/
    /*        padding: 20px 0;*/
    /*    }*/

    /*    评论区样式1 */
        /* 新增评论区域样式 */
        .comment-section {
            display: flex;
            flex-direction: column;
            height: 500px; /* 固定高度 */
        }

        .comment-list {
            flex: 1;
            overflow-y: auto;
            padding-right: 10px;
            margin: 15px 0;
        }

        /* 美化滚动条 */
        .comment-list::-webkit-scrollbar {
            width: 6px;
        }
        .comment-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        .comment-list::-webkit-scrollbar-thumb {
            background: #c0c4cc;
            border-radius: 3px;
        }
        .comment-list::-webkit-scrollbar-thumb:hover {
            background: #909399;
        }

        /* 固定底部操作栏 */
        .comment-form {
            position: sticky;
            bottom: 0;
            background: white;
            padding: 15px 0;
            box-shadow: 0 -4px 12px rgba(0,0,0,0.05);
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .comment-section {
                height: 60vh; /* 视口高度百分比 */
            }
        }
    </style>

</head>

<body>
<div id="app">
    <div class="community-container">
        <!-- 头部 -->
        <div class="header">
            <h1>社区论坛</h1>
            <el-button type="primary" icon="el-icon-edit" @click="showPostForm = true">
                我要发帖
            </el-button>
        </div>

        <!-- 帖子列表 -->
        <el-row :gutter="20">
            <el-col v-for="post in posts" :key="post.id" :xs="24" :sm="12" :md="8" :lg="6">
                <el-card class="post-card">
                    <h3>{{ post.title }}</h3>
                    <div class="post-meta">
                        <el-tag size="mini"><i class="el-icon-user"></i> {{ post.userId }}</el-tag>
                        <el-tag size="mini" type="info"><i class="el-icon-time"></i> {{ formatDate(post.createdAt) }}</el-tag>
                        <el-tag size="mini" type="warning"><i class="el-icon-star-on"></i> {{ post.good }}</el-tag>
                    </div>
                    <el-button type="text" @click="showPostDetails(post)">查看详情</el-button>
                </el-card>
            </el-col>
        </el-row>

        <!-- 发帖对话框 -->
        <el-dialog
                title="发表新帖"
                :visible.sync="showPostForm"
                width="600px">
            <el-form ref="postForm" :model="form" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input
                            type="textarea"
                            :rows="4"
                            v-model="form.content"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="image">
                    <el-upload
                            action="#"
                            :auto-upload="false"
                            :on-change="handleFileChange">
                        <el-button size="small">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">支持jpg/png格式，大小不超过5MB</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer">
                    <el-button @click="showPostForm = false">取消</el-button>
                    <el-button
                            type="primary"
                            :loading="submitting"
                            @click="submitPost">提交</el-button>
                </span>
        </el-dialog>

        <!-- 帖子详情对话框 -->
        <el-dialog :title="selectedPost.title" :visible.sync="showDetail" width="800px">
            <div class="post-detail">
                <!-- 添加帖子内容 -->
                <div class="post-content">
                    <p style="white-space: pre-wrap;">{{ selectedPost.content }}</p>
                    <el-image v-if="selectedPost.picture" :src="selectedPost.picture"
                              :preview-src-list="[selectedPost.picture]" class="post-image">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                </div>

                <div class="post-header">
                    <el-button type="warning" icon="el-icon-star-off" @click="likePost(selectedPost.id)">
                        点赞（{{ selectedPost.good }}）
                    </el-button>
                </div>

                <!-- 评论区域 -->
                <div class="comment-section">
                    <h3 class="comment-title">评论（{{ totalComments }}）</h3>

                    <!-- 评论列表 -->
                    <div class="comment-list">
                        <div v-for="comment in comments" :key="comment.id" class="comment-item">
                            <div class="comment-header">
                                <span class="user-name">用户 {{ comment.userId }}</span>
                                <span class="comment-time">{{ formatDateCM(comment.createAt) }}</span>
                            </div>
                            <p class="comment-text">{{ comment.content }}</p>
                        </div>
                    </div>

                    <!-- 分页 -->
                    <el-pagination background :page-size="pageSize" :current-page="currentPage" :total="totalComments"
                                   layout="prev, pager, next" @current-change="handlePageChange">
                    </el-pagination>

                    <!-- 发表评论 -->
                    <div class="comment-form">
                        <el-input type="textarea" :rows="3" v-model="commentForm.content" placeholder="写下你的评论..." resize="none">
                        </el-input>
                        <div class="form-actions">
                            <el-button type="primary" size="medium" @click="submitComment">
                                发表评论
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</div>

<script src="./vue/vue.js"></script>
<script src="./element-ui/index.js"></script>
<script src="./axios/axios.min.js"></script>

<script>
    // Cookie处理函数
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }

    // 配置axios拦截器
    axios.interceptors.request.use(config => {
        const token = getCookie('token');
        if (token) {
            config.headers['Authorization'] = token;
        }
        return config;
    });

    Vue.use(ELEMENT);

    new Vue({
        el: '#app',
        data() {
            return {
                submitting: false,
                rules: {
                    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
                    content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
                },
                posts: [],
                showPostForm: false,
                form: {
                    title: '',
                    content: '',
                    image: null
                },
                selectedPost: {},
                showDetail: false,
                comments: [],
                commentForm: {
                    content: ''
                },
                currentPage: 1,
                pageSize: 10,
                totalComments: 0
            }
        },
        mounted() {
            this.fetchPosts();
        },
        methods: {
            handleFileChange(file) {
                this.form.image = file.raw;
            },

            async submitPost() {
                try {
                    // 表单验证
                    const valid = await this.$refs.postForm.validate();
                    if (!valid) return;

                    // 防止重复提交
                    if (this.submitting) return;
                    this.submitting = true;

                    // 构建表单数据
                    const formData = new FormData();
                    formData.append('title', this.form.title);
                    formData.append('content', this.form.content);
                    if (this.form.image) {
                        formData.append('file', this.form.image);
                    }

                    // 提交请求
                    const res = await axios.post('http://localhost:8000/user/post', formData, {
                        headers: { 'Content-Type': 'multipart/form-data',
                            'Authorization': getCookie('token')

                        }
                    });

                    if (res.data.code === 200) {
                        this.$message.success('发帖成功');
                        this.showPostForm = false;
                        this.$refs.postForm.resetFields();
                        this.form.image = null;
                        this.fetchPosts();
                    }else if(res.data.code === 119){
                        // 清空cookie
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        window.location.href = 'http://localhost:5173';
                    }
                } catch (error) {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    this.$message.error(error.response?.data?.msg || '提交失败');
                }  finally {
                    this.submitting = false;
                }
            },

            // 获取帖子列表
            async fetchPosts() {
                try {
                    const res = await axios.get('http://localhost:8000/user/post');
                    if (res.data.code === 200) {
                        this.posts = res.data.data;
                    }else if(res.data.code === 119){
                        // 清空cookie
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        window.location.href = 'http://localhost:5173';
                    }
                } catch (error) {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    this.$message.error('获取帖子失败');
                }
            },

            // 点赞功能
            async likePost(postId) {
                try {
                    const res = await axios.put(`http://localhost:8000/user/post/${postId}/good`);
                    if (res.data.code === 200) {
                        this.$message.success('点赞成功');
                        this.selectedPost.good += 1;
                    }else if(res.data.code === 119){
                        // 清空cookie
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        window.location.href = 'http://localhost:5173';
                    } else {
                        this.$message.info('您已经点过赞了');
                    }
                } catch (error) {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    this.$message.error('点赞失败');
                }
            },


            // 提交评论
            async submitComment() {
                if (!this.commentForm.content) {
                    this.$message.error('请输入评论内容');
                    return;
                }

                try {
                    const res = await axios.post('http://localhost:8000/user/comment', {
                        postId: this.selectedPost.id,
                        content: this.commentForm.content
                    });

                    if (res.data.code === 200) {
                        this.$message.success('评论成功');
                        this.commentForm.content = '';
                        this.fetchComments(this.selectedPost.id);
                    }else if(res.data.code === 119){
                        // 清空cookie
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        window.location.href = 'http://localhost:5173';
                    }
                } catch (error) {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    this.$message.error('评论失败');
                }
            },

            // 分页处理
            handlePageChange(page) {
                this.currentPage = page;
                this.fetchComments(this.selectedPost.id);
            },

            // 获取评论
            async fetchComments(postId) {
                try {
                    const res = await axios.get(`http://localhost:8000/user/comment/${postId}`, {
                        params: {
                            page: this.currentPage,
                            size: this.pageSize
                        }
                    });

                    if (res.data.code === 200) {
                        this.comments = res.data.data.records;
                        this.totalComments = res.data.data.total;
                    }else if(res.data.code === 119){
                        // 清空cookie
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        window.location.href = 'http://localhost:5173';
                    }
                } catch (error) {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    this.$message.error('获取评论失败');
                }
            },

            // 显示帖子详情
            async showPostDetails(post) {
                this.selectedPost = post;
                this.showDetail = true;
                this.currentPage = 1; // 重置分页
                await this.fetchComments(post.id);
            },

            // 时间格式化方法
            formatDate(date) {
                return new Date(date).toLocaleDateString();
            },
            formatDateCM(dateString) {
                return dateString ? new Date(dateString).toLocaleString() : '';
            }
        }
    });
</script>
</body>

</html>
